package models

import (
	"github.com/spf13/cast"
	"time"
)

// MerchantOrderDynamicStatistics 统计商户订单活跃表
type MerchantOrderDynamicStatistics struct {
	Model
	MerchantId int       `json:"merchant_id" gorm:"comment:'商户id'"`
	OrderNum   int       `json:"transaction_num" gorm:"comment:'连续交易天数'"`
	OverAt     time.Time `json:"over_at" gorm:"comment:'连续交易最后一天'"`
}

// AddMerchantOrderDynamicStatistics 添加数据
func AddMerchantOrderDynamicStatistics(merchantId any) error {
	// 获取昨天的开始时间
	yesterday := time.Now().AddDate(0, 0, -1)
	yesterdayStart := time.Date(yesterday.Year(), yesterday.Month(), yesterday.Day(), 0, 0, 0, 0, yesterday.Location())

	var statis *MerchantOrderDynamicStatistics
	db.Where("merchant_id = ? AND over_at >= ?", merchantId, yesterdayStart).First(&statis)
	if statis.ID == 0 {
		//没有交易记录,创建记录
		db.Create(&MerchantOrderDynamicStatistics{
			MerchantId: cast.ToInt(merchantId),
			OrderNum:   1,
			OverAt:     time.Now(),
		})
		return nil
	}

	if !IsToday(statis.OverAt) {
		//最后一次交易不是今天
		statis.OrderNum += 1
	}
	statis.OverAt = time.Now()

	db.Updates(statis)

	return nil
}

// GetMerchantOrderDynamicNum 获取活跃商户与商户总数
func GetMerchantOrderDynamicNum(agentId, condition any) map[string]interface{} {
	var result map[string]interface{}
	db.Model(&MerchantRelation{}).Select("COUNT( DISTINCT merchant_order_dynamic_statistics.id ) AS dynamic_num ,COUNT(DISTINCT merchant_relations.id) AS merchant_num").
		Joins("LEFT JOIN merchant_order_dynamic_statistics ON merchant_relations.merchant_id = merchant_order_dynamic_statistics.merchant_id AND merchant_order_dynamic_statistics."+cast.ToString(condition)).
		Where("merchant_relations.agent_id = ?", agentId).First(&result)

	return result
}

// IsOverAtYesterday 判断OverAt字段是否为昨天的时间
func (m *MerchantOrderDynamicStatistics) IsOverAtYesterday() bool {
	// 获取昨天的开始和结束时间（这里我们假设一天从00:00:00开始到23:59:59结束）
	yesterdayStart := time.Now().AddDate(0, 0, -1).Truncate(24 * time.Hour)
	yesterdayEnd := yesterdayStart.Add(24*time.Hour - time.Second)

	// 比较OverAt是否在昨天的时间范围内
	return m.OverAt.After(yesterdayStart) && m.OverAt.Before(yesterdayEnd)
}

// IsToday 判断给定的 time.Time 是否是今天
func IsToday(t time.Time) bool {
	// 获取今天的日期部分（0时0分0秒）
	today := time.Now().Truncate(24 * time.Hour)
	// 判断给定的时间 t 的日期部分是否与今天相同
	return t.Truncate(24 * time.Hour).Equal(today)
}
